package com.ruoyi.aitcommon.controller;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.anotation.ApiLog;
import com.ruoyi.aitcommon.utils.*;
import com.ruoyi.aitcommon.vo.RestCallVO;
import com.ruoyi.aitcommon.vo.RuntimeVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.aitcommon.domain.AitLog;
import com.ruoyi.aitcommon.service.IAitLogService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 接口日志Controller
 * 
 * @author cli
 * @date 2021-06-19
 */
@RestController
@RequestMapping("/aitcommon/aitlog")
public class AitLogController extends BaseController
{
    @Autowired
    private IAitLogService aitLogService;

    @ApiLog("加载REST调用信息")
    @GetMapping("/loadCallInfo")
    public JSONObject loadCallInfo(String logID) {
        JSONObject retjosn=new JSONObject();
        try{
            if(StrUtil.isBlank(logID))
                throw new Exception("传入logID为空");
            final AitLog aitLog = aitLogService.selectAitLogById(Long.valueOf(logID));
            if(aitLog==null) throw new Exception("AitLog查询失败!");

//                构造返回信息
            RuntimeVO runInfo = new RuntimeVO();
            runInfo.setFlowID(aitLog.getFlowId());
            runInfo.setFlowCode(aitLog.getFlowCode());
            runInfo.setFlowName(aitLog.getFlowName());
            runInfo.setStartTime(aitLog.getStartDate());
            runInfo.setEndTime(aitLog.getEndDate());
            retjosn = (JSONObject) JSONObject.toJSON(runInfo);
//                构造rest调用信息
            List<RestCallVO> callList = new ArrayList<>();
            RestCallVO callvo=new RestCallVO();
            callvo.setUrl(aitLog.getOperUrl());
            callvo.setMethod(aitLog.getReqMethod());

            final Object headstr = aitLog.getParField0();
            if (JSONUtils.validJSONObjectStr(headstr.toString())) {
                final Object json = JSONObject.parse(headstr.toString());
                if(ObjUtils.isNotBlank(json)){
                    String ret = JSONObject.toJSONString(json);
                    callvo.setHead(ret);
                }
            }

            final Object bodystr = aitLog.getInParam();
            if (JSONUtils.validJSONObjectStr(bodystr.toString())) {
                final Object json = JSONObject.parse(bodystr.toString());
                if(ObjUtils.isNotBlank(json)){
                    String ret = JSONObject.toJSONString(json, true);
                    callvo.setBody(ret);
                }
            }
            final Object response = aitLog.getRetParam();
            if (JSONUtils.validJSONObjectStr(response.toString())) {
                final Object json = JSONObject.parse(response.toString());
                if(ObjUtils.isNotBlank(json)){
                    String ret = JSONObject.toJSONString(json, true);
                    callvo.setResponse(ret);
                }
            }

            callList.add(callvo);
            retjosn.put("restCall", callList);

            return JSONResult.success(retjosn);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    /**
     * 查询接口日志列表
     */
    @PreAuthorize("@ss.hasPermi('aitcommon:aitlog:list')")
    @GetMapping("/list")
    public TableDataInfo list(AitLog aitLog)
    {
        startPage();
        List<AitLog> list = aitLogService.selectAitLogList(aitLog);
        return getDataTable(list);
    }

    /**
     * 导出接口日志列表
     */
    @PreAuthorize("@ss.hasPermi('aitcommon:aitlog:export')")
    @Log(title = "接口日志", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AitLog aitLog)
    {
        List<AitLog> list = aitLogService.selectAitLogList(aitLog);
        ExcelUtil<AitLog> util = new ExcelUtil<AitLog>(AitLog.class);
        return util.exportExcel(list, "接口日志数据");
    }

    /**
     * 获取接口日志详细信息
     */
    @PreAuthorize("@ss.hasPermi('aitcommon:aitlog:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(aitLogService.selectAitLogById(id));
    }

    /**
     * 新增接口日志
     */
    @PreAuthorize("@ss.hasPermi('aitcommon:aitlog:add')")
    @Log(title = "接口日志", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AitLog aitLog)
    {
        return toAjax(aitLogService.insertAitLog(aitLog));
    }

    /**
     * 修改接口日志
     */
    @PreAuthorize("@ss.hasPermi('aitcommon:aitlog:edit')")
    @Log(title = "接口日志", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AitLog aitLog)
    {
        return toAjax(aitLogService.updateAitLog(aitLog));
    }

    /**
     * 删除接口日志
     */
    @PreAuthorize("@ss.hasPermi('aitcommon:aitlog:remove')")
    @Log(title = "接口日志", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(aitLogService.deleteAitLogByIds(ids));
    }
}
